<template>
  <div class="content app-main-content-box">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      class="demo-ruleForm"
    >
      <el-form-item label="广告名" prop="name">
        <el-input
          v-model="ruleForm.name"
          maxlength="10"
          show-word-limit
          placeholder="请输入广告名"
        />
      </el-form-item>
      <el-form-item label="广告位" prop="no">
        <el-select v-model="ruleForm.no" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告图" prop="picUrl">
        <div class="upload-container">
          <el-upload
            :action="imageUploadUrl"
            :show-file-list="false"
            :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
            :before-upload="
              (file) => {
                return handleImgBefore(file, 1);
              }
            "
            :on-success="
              (res, file) => {
                return handleImgSuccess(res, file, 'picUrl');
              }
            "
            class="app-uploader-img-plus"
            style="width: 120px; height: 120px"
          >
            <el-image
              v-if="ruleForm.picUrl"
              :src="ruleForm.picUrl"
              style="width: 120px; height: 120px"
              class="img"
              fit="fill"
            />
            <i
              v-else
              class="el-icon-plus"
              style="width: 120px; height: 120px"
            />
          </el-upload>
          <el-button
            v-if="ruleForm.picUrl"
            type="text"
            size="small"
            style="margin-left: 10px"
            class="app-text-color-danger"
            @click="ruleForm.picUrl = ''"
          >删除LOGO
          </el-button>
        </div>
        <div class="tips-text">
          图片建议尺寸：120*120像素，大小不超过1M，支持JPG、PNG，如果不传默认使用当前类型的LOGO。
        </div>
      </el-form-item>
      <el-form-item label="跳转内容" prop="innerPageJson">
        <div>
          <el-radio-group v-model="ruleForm.mode">
            <el-radio label="self">站内链接</el-radio>
            <el-radio label="wx_app">小程序</el-radio>
          </el-radio-group>
          <div v-if="ruleForm.mode === 'self'">
            <el-button @click="handleOpenSelfPage">设置</el-button>
            <div v-if="ruleForm.innerPageJson.title">
              路径： {{ ruleForm.innerPageJson.title }}
            </div>
          </div>

          <div v-if="ruleForm.mode === 'wx_app'">
            <el-form
              ref="wxAppFormRef"
              :model="ruleForm"
              :rules="wxAppFormRules"
              label-width="130px"
              label-position="left"
            >
              <el-form-item label="小程序appid" prop="thirdAppId">
                <el-input
                  v-model="ruleForm.thirdAppId"
                  placeholder="请输入小程序appid"
                  :maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="小程序路径" prop="thirdAppPath">
                <el-input
                  v-model="ruleForm.thirdAppPath"
                  placeholder="请输入小程序路径"
                  :maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="time" label="投放时间段">
        <el-date-picker
          v-model="ruleForm.time"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="pageType === 'add'"
          type="primary"
          :disabled="isCanSubmit"
          @click="submitForm('ruleForm')"
        >立即创建</el-button>
        <el-button
          v-if="pageType === 'edit'"
          type="primary"
          :disabled="isCanSubmit"
          @click="submitForm('ruleForm')"
        >保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <app-self-table
      ref="appSelfTableRef"
      @submit="(e) => (ruleForm.innerPageJson = e)"
    />
  </div>
</template>

<script>
import { imgUploadUrl } from '@/api/upload'
import { mapGetters } from 'vuex'
import { AdvertisingPosition } from '@/publicViews/operationCenter/AdvertisingManager/const'
import appSelfTable from '../../components/appSelfTable'
import { addAdvert, getWiFiDetail, updateAdvert } from '@/api/advertising'
export default {
  components: { appSelfTable },
  data() {
    return {
      ruleForm: {
        name: '',
        no: AdvertisingPosition.POSITION_1,
        picUrl: '',
        time: '',
        startTime: '',
        endTime: '',
        mode: 'self',
        thirdAppId: '',
        thirdAppPath: '',
        innerPageJson: ''
      },
      options: [
        {
          label: 'WiFi连接位一',
          value: AdvertisingPosition.POSITION_1
        },
        {
          label: 'WiFi连接成功位',
          value: AdvertisingPosition.POSITION_SUCCESS
        }
      ],
      rules: {
        name: [{ required: true, message: '请输入广告名', trigger: 'blur' }],
        no: [{ required: true, message: '请选择广告位', trigger: 'blur' }],
        picUrl: [{ required: true, message: '请输入广告图', trigger: 'blur' }],
        time: [
          { required: true, message: '请输入投放时间段', trigger: 'blur' }
        ],
        mode: [{ required: true, message: '请输入跳转内容', trigger: 'blur' }]
      },
      wxAppFormRules: {
        thirdAppId: [
          { required: true, message: '请输入小程序appid', trigger: 'blur' }
        ],
        thirdAppPath: [
          { required: true, message: '请输入小程序路径', trigger: 'blur' }
        ]
      },
      imageUploadUrl: imgUploadUrl,
      tempData: {
        thirdAppId: '',
        thirdAppPath: '',
        innerPageJson: ''
      }
    }
  },
  watch: {
    'ruleForm.mode': {
      handler(val) {
        if (val === 'self') {
          this.ruleForm.thirdAppId = ''
          this.ruleForm.thirdAppPath = ''
          this.ruleForm.innerPageJson = this.tempData.innerPageJson
          this.rules.innerPageJson = [
            { required: true, message: '请选择跳转内容', trigger: 'blur' }
          ]
        }
        if (val === 'wx_app') {
          this.ruleForm.thirdAppId = this.tempData.thirdAppId
          this.ruleForm.thirdAppPath = this.tempData.thirdAppPath
          this.ruleForm.innerPageJson = ''
          this.rules.innerPageJson = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm']),
    pageType({ $route }) {
      return $route.query.type
    },
    isCanSubmit({ ruleForm }) {
      return !(!!ruleForm.name && !!ruleForm.picUrl && !!ruleForm.time)
    }
  },
  created() {
    if (this.$route.query.type === 'edit') {
      this.fetchData()
      this.$route.meta.title = '编辑'
    }
  },
  methods: {
    // 如果是编辑获取详情
    async fetchData() {
      const res = await getWiFiDetail({ id: this.$route.query.id })
      if (res?.code === 0) {
        const data = res.data
        data.time = [data.startTime, data.endTime]
        if (data.innerPageJson) {
          data.innerPageJson = JSON.parse(data.innerPageJson)
        }
        data.mode = data.thirdAppId && data.thirdAppPath ? 'wx_app' : 'self'
        this.ruleForm = { ...data }
        this.tempData = { ...data }
      }

      console.log('===', res)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.mode === 'wx_app') {
            this.$refs?.wxAppFormRef?.validate((wxvalid) => {
              if (wxvalid) {
                this.handleSubmit()
              }
            })
          }
          if (this.ruleForm.mode === 'self') {
            this.handleSubmit()
          }
        } else {
          if (this.ruleForm.mode === 'wx_app') {
            this.$refs?.wxAppFormRef.validate()
          }
          return false
        }
      })
    },
    async handleSubmit() {
      const {
        name,
        no,
        picUrl,
        time,
        thirdAppId,
        thirdAppPath,
        innerPageJson
      } = this.ruleForm
      const params = {
        name,
        no,
        picUrl,
        startTime: time[0],
        endTime: time[1],
        thirdAppId,
        thirdAppPath,
        innerPageJson: JSON.stringify(innerPageJson)
      }
      if (this.$route.query.type === 'add') {
        const res = await addAdvert(params)
        if (res?.code === 0) {
          this.$message.success('新增成功')
          setTimeout(() => {
            this.$router.go(-1)
          }, 3000)
        }
        return
      }
      if (this.$route.query.type === 'edit') {
        // 保存
        params.id = this.ruleForm.id
        const res = await updateAdvert(params)
        if (res?.code === 0) {
          this.$message.success('保存成功')
          setTimeout(() => {
            this.$router.go(-1)
          }, 3000)
        }
        return
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs?.wxAppFormRef?.resetFields()
    },

    // 上传图标之前
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF'])
    },

    // 上传图标成功
    handleImgSuccess(res, file, type) {
      if (res.code === 0) {
        this.ruleForm[type] = res.data.baseUrl + res.data.path
        this.$refs.ruleForm.clearValidate([type])
      } else {
        this.$message.error(res.msg)
      }
    },
    handleOpenSelfPage() {
      this.$refs.appSelfTableRef.handleOpen()
    }
  }
}
</script>

<style scoped lang="scss">
/* 上传图片 */
.upload-container {
  display: flex;

  .el-icon-plus {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    color: #8c939d;
  }

  .img {
    display: block;
  }
}
.el-input {
  width: 300px;
}
.el-form-item {
  margin-bottom: 20px;
}
</style>
